# -*- coding:utf-8 -*-
# 微信聊天记录的图片DAT文件还原 
import os
 
into_path = r'D:/test1'  # 微信图片DAT文件存放路径
out_path = r"D:/test2"   # 转换后的图片存放路径
 
def main(into_path, out_path):
    dat_list = dat_files(into_path)
    lens = len(dat_list)
    if lens == 0:
        print('没有dat文件')
        exit()
    num = 0
    for dat_file in dat_list:
        num += 1
        temp_path = into_path + '/' + dat_file
        dat_file_name = dat_file[:-4]
        imageDecode(temp_path, dat_file_name, out_path)
        value = round((num / lens) * 100, 2)
        print('正在处理--->[{}/{}] {}%'.format(num, lens, value))
 
def dat_files(file_dir):
    dat = []
    for files in os.listdir(file_dir):
        if os.path.splitext(files)[1] == '.dat':
            dat.append(files)
    return dat
 
def imageDecode(temp_path, dat_file_name, out_path):
    dat_read = open(temp_path, "rb")
    xo, j = Format(temp_path)
    if j == 1:
        mat = '.png'
    elif j == 2:
        mat = '.gif'
    else:
        mat = '.jpg'
    out = out_path + '/' + dat_file_name + mat
    png_write = open(out, "wb")
    dat_read.seek(0)
    for now in dat_read:
        for nowByte in now:
            newByte = nowByte ^ xo
            png_write.write(bytes([newByte]))
    dat_read.close()
    png_write.close()
 
 
def Format(f):
    dat_r = open(f, "rb")
    try:
        a = [(0x89, 0x50, 0x4e), (0x47, 0x49, 0x46), (0xff, 0xd8, 0xff)]
        for now in dat_r:
            j = 0
            for xor in a:
                j = j + 1
                i = 0
                res = []
                now2 = now[:3]
                for nowByte in now2:
                    res.append(nowByte ^ xor[i])
                    i += 1
                if res[0] == res[1] == res[2]:
                    return res[0], j
    except:
        pass
    finally:
        dat_r.close()
 
 
if __name__ == '__main__':
    main(into_path, out_path)